<template>
	<div class="article-list">
		<van-pull-refresh success-duration="1000" :success-text="refreshSuccessText" v-model="isreFreshLoading"
			@refresh="onRefresh">
			<van-list :error.sync="error" error-text="请求失败，点击重新加载" v-model="loading" :finished="finished"
				finished-text="没有更多了" @load="onLoad">
				<ArticleItem v-for="(article, index) in list" :key="index" :article="article"></ArticleItem>
			</van-list>
		</van-pull-refresh>
	</div>
</template>

<script>
	import {
		getArticles
	} from '@/api/article.js'
	import ArticleItem from '@/components/article-item'

	export default {
		components: {
			ArticleItem
		},
		
		props: {
			channel: {
				type: Object,
				required: true
			},
		},

		data() {
			return {
				list: [],
				loading: false,
				finished: false,
				timestamp: null,
				error: false,
				isreFreshLoading: false,
				refreshSuccessText: '刷新成功'
			};
		},
		methods: {
			async onLoad() {
				try {
					const {
						data: res
					} = await getArticles({
						channel_id: this.channel.id,
						timestamp: this.timestamp || Date.now(),
					})

					const {
						results
					} = res.data
					this.list.push(...results)
					this.loading = false

					if (results.length) {
						this.timestamp = res.data.pre_timestamp
					} else {
						this.finished = true
					}
				} catch (e) {
					this.loading = false
					this.error = true
				}
			},

			async onRefresh() {
				try {
					const {
						data: res
					} = await getArticles({
						channel_id: this.channel.id,
						timestamp: this.timestamp || Date.now(),
					})

					const {
						results
					} = res.data
					this.list.unshift(...results)
					this.isreFreshLoading = false
					this.refreshSuccessText = `刷新成功，更新了${results.length}条数据`

					if (results.length) {
						this.timestamp = res.data.pre_timestamp
					} else {
						this.refreshSuccessText = '没有更多数据了'
					}

				} catch (e) {
					this.isreFreshLoading = false
					this.refreshSuccessText = '刷新失败'
				}
			},
		},
	}
</script>

<style lang="less" scoped>
	.article-list {
		height: 79vh;
		overflow-y: auto;
	}
</style>
